package com.tbit.uqbike.client.remote.nameauth;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.net.URLEncoder;

/**
 * 寻程实名认证接口
 *
 * @author Leon
 * 2015-8-28 下午05:29:38
 */
public class XCHttpClient {
    private final static Logger log = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
    private static HttpClient client = null;
    /**
     * 大哈实名认证的key
     */
    private static String key = "";

    /**
     * 维持单session
     */
    public static HttpClient getClient() {
        if (client == null) {
            MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
            client = new HttpClient(connectionManager);
            /**设置编码*/
            client.getParams().setContentCharset("UTF-8");
            /**请求超时*/
            client.getHttpConnectionManager().getParams().setConnectionTimeout(1000);
            /**读取超时*/
            client.getHttpConnectionManager().getParams().setSoTimeout(5000);
        }
        return client;
    }


    /**
     * 实名认证
     *
     * @param authNameKey
     * @param idNO
     * @param name
     * @return
     */
    public static Boolean authName(String authNameKey, String idNO, String name) {
        HttpClient client = getClient();
        GetMethod get = null;
        try {
            get = new GetMethod("http://v.apistore.cn/api/a1?key=" + authNameKey + "&cardNo=" + idNO + "&realName=" + URLEncoder.encode(name, "UTF-8"));
            client.executeMethod(get);
            String result = get.getResponseBodyAsString();
            log.info(result);
            JSONObject object = JSONObject.parseObject(result);
            Integer state = object.getInteger("error_code");
            if (state == 0) {
                return true;
            }
        } catch (Exception e) {
            log.error("实名认证异常", e);
        } finally {
            get.releaseConnection();
        }

        return false;
    }

    public static void main(String[] args) {
        System.out.println(authName("364663d940b63cda2e857680f", "130425199609034227", "吕乐园"));
    }
}